package com.jia.train.batch.controller;

import cn.hutool.core.date.DateTime;
import com.jia.train.batch.request.CronJobRequest;
import com.jia.train.batch.response.CronJobResponse;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/job")
public class JobController {

    public static final Logger logger = LoggerFactory.getLogger(JobController.class);

    private final SchedulerFactoryBean schedulerFactoryBean;

    public JobController(SchedulerFactoryBean schedulerFactoryBean) {
        this.schedulerFactoryBean = schedulerFactoryBean;
    }

    @PostMapping("run")
    public ResponseEntity<?> runJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String group = request.getJobClassGroup();
        try {
            logger.info("手工执行定时任务开始：{}，{}", name, group);
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.triggerJob(JobKey.jobKey(name, group));
        } catch (SchedulerException e) {
            logger.info("手工执行定时任务开始失败：{}", e.getMessage());
        }
        return ResponseEntity.ok().build();
    }


    @PostMapping("add")
    public ResponseEntity<?> createJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String description = request.getDescription();
        String group = request.getJobClassGroup();
        String cronExpression = request.getCronExpression();
        logger.info("创建定时任务开始：{}, {}, {}, {}", name, description, group, cronExpression);
        try {
            // schedulerFactoryBean 获取一个调度器实例
            Scheduler scheduler = schedulerFactoryBean.getScheduler();

            // 启动调度器
            scheduler.start();

            // 构建job信息
            JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(name))
                    .withIdentity(name, group)
                    .withDescription(description)
                    .build();

            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);

            // 按新的cronExpression表达式构建trigger
            CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                    .withIdentity(name, group)
                    .withDescription(description)
                    .withSchedule(cronScheduleBuilder)
                    .build();

            scheduler.scheduleJob(jobDetail, cronTrigger);

        } catch (SchedulerException e) {
            logger.info("调度错误：{}", e.getMessage());
        } catch (ClassNotFoundException e) {
            logger.info("找不到传入的类：{}", e.getMessage());
        }
        return ResponseEntity.ok().build();
    }

    @PostMapping("pause")
    public ResponseEntity<?> pauseJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String group = request.getJobClassGroup();
        try {
            logger.info("暂停定时任务开始：{}，{}", name, group);
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.pauseJob(JobKey.jobKey(name, group));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok().build();
    }

    @PostMapping("resume")
    public ResponseEntity<?> resumeJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String group = request.getJobClassGroup();
        try {
            logger.info("重启定时任务开始：{}，{}", name, group);
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.resumeJob(JobKey.jobKey(name, group));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok().build();
    }

    @PostMapping("reschedule")
    public ResponseEntity<?> rescheduleJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String description = request.getDescription();
        String group = request.getJobClassGroup();
        String cronExpression = request.getCronExpression();
        DateTime now = DateTime.now();
        logger.info("重置定时任务开始：{}, {}, {}, {}", name, description, group, cronExpression);
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            TriggerKey triggerKey = TriggerKey.triggerKey(name, group);

            // 表达式调度构建器
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
            CronTriggerImpl trigger = (CronTriggerImpl) scheduler.getTrigger(triggerKey);
            trigger.setStartTime(now);

            CronTrigger cronTrigger = trigger;

            cronTrigger = cronTrigger.getTriggerBuilder()
                    .withIdentity(triggerKey)
                    .withDescription(description)
                    .build();

            scheduler.rescheduleJob(triggerKey, cronTrigger);

        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }

        return ResponseEntity.ok().build();
    }

    @DeleteMapping("delete")
    public ResponseEntity<?> deleteJob(@RequestBody CronJobRequest request) {
        String name = request.getJobClassName();
        String group = request.getJobClassGroup();
        logger.info("删除定时任务开始：{}，{}", name, group);
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            scheduler.pauseTrigger(TriggerKey.triggerKey(name, group));
            scheduler.unscheduleJob(TriggerKey.triggerKey(name, group));
            scheduler.deleteJob(JobKey.jobKey(name, group));
        } catch (SchedulerException e) {
            logger.info("删除定时任务失败：{}", e.getMessage());
        }
        return ResponseEntity.ok().build();
    }


    @GetMapping("query")
    public ResponseEntity<?> queryJob() {
        logger.info("查询所有定时任务");
        List<CronJobResponse> responseList = new ArrayList<>();
        try {
            Scheduler scheduler = schedulerFactoryBean.getScheduler();
            for (String jobGroupName : scheduler.getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.jobGroupEquals(jobGroupName))) {
                    CronJobResponse response = new CronJobResponse();
                    response.setJobClassName(jobKey.getName());
                    response.setJobClassGroup(jobKey.getGroup());
                    List<Trigger> triggers = (List<Trigger>) scheduler.getTriggersOfJob(jobKey);
                    CronTrigger cronTrigger = (CronTrigger) triggers.get(0);
                    response.setCronExpression(cronTrigger.getCronExpression());
                    response.setNextFireTime(cronTrigger.getNextFireTime());
                    response.setPrevFireTime(cronTrigger.getPreviousFireTime());
                    response.setDescription(cronTrigger.getDescription());

                    TriggerKey triggerKey = cronTrigger.getKey(); // 获取触发器自身的Key
                    response.setState(scheduler.getTriggerState(triggerKey)); // 正确获取状态

                    responseList.add(response);
                }
            }
            return ResponseEntity.ok(responseList);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

}
